package map.tile.server.common;

import map.tile.server.dto.BoundingBox;
import map.tile.server.dto.TileIndex;

public  class Translate {



    /**
     * 根据经纬度和缩放等级，求得瓦片路径
     * **/
    public static TileIndex getTileNumber(double lat, double lon, int zoom) {
        int xtile = (int)Math.floor( (lon + 180) / 360 * (1<<zoom) ) ;
        int ytile = (int)Math.floor( (1 - Math.log(Math.tan(Math.toRadians(lat)) + 1 / Math.cos(Math.toRadians(lat))) / Math.PI) / 2 * (1<<zoom) ) ;
        if (xtile < 0)
            xtile=0;
        if (xtile >= (1<<zoom))
            xtile=((1<<zoom)-1);
        if (ytile < 0)
            ytile=0;
        if (ytile >= (1<<zoom))
            ytile=((1<<zoom)-1);

        return new TileIndex(zoom,xtile,ytile);
    }


    /**
     * 瓦片获得范围
     * **/
    public static BoundingBox tile2boundingBox(final int x, final int y, final int zoom) {
        BoundingBox bb=new BoundingBox();
        bb.setLatMax(tile2lat(y, zoom));
        bb.setLatMin(tile2lat(y + 1, zoom));
        bb.setLonMin( tile2lon(x, zoom));
        bb.setLonMax(tile2lon(x + 1, zoom));
        return bb;
    }
    /**
     * 瓦片获得范围
     * **/
    public static BoundingBox tile2boundingBox(TileIndex tileIndex) {
        BoundingBox bb=new BoundingBox();
        bb.setLatMax(tile2lat(tileIndex.getY(), tileIndex.getZ()));
        bb.setLatMin(tile2lat(tileIndex.getY() + 1, tileIndex.getZ()));
        bb.setLonMin( tile2lon(tileIndex.getX(), tileIndex.getZ()));
        bb.setLonMax(tile2lon(tileIndex.getX() + 1, tileIndex.getZ()));
        return bb;
    }

    /**
     * 瓦片转换经度
     * **/
    public static double tile2lon(long x, int z) {
        return x / Math.pow(2.0, z) * 360.0 - 180;
    }

    /**
     *瓦片转换纬度
     * @author  2018年8月13日 下午7:44:08
     * @param y
     * @param z
     * @return
     * @modify {原因} by  2018年8月13日 下午7:44:08
     */
    public static double tile2lat(long y, int z) {
        double n = Math.PI - (2.0 * Math.PI * y) / Math.pow(2.0, z);
        return Math.toDegrees(Math.atan(Math.sinh(n)));
    }



}
